<?php
namespace app\controller;

use Webman\Http\Request;
use app\model\User;

class BaseController
{

    protected $noNeedLogin = [];

    /**
     * 获取当前登录用户
     * @param Request $request
     * @return User|null
     */
    protected function getUser(Request $request)
    {
        if (!isset($request->user)) {
            return null;
        }
        return User::find($request->user['extend']['id']);
    }

    /**
     * 获取当前登录用户ID
     * @param Request $request
     * @return int|null
     */
    protected function getUserId(Request $request)
    {
        return $request->user['extend']['id'] ?? null;
    }

    /**
     * 成功响应
     * @param mixed $data
     * @param string $msg
     * @return \Webman\Http\Response
     */
    protected function success($data = null, string $msg = 'success')
    {
        return json([
            'code' => 200,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 错误响应
     * @param string $msg
     * @param int $code
     * @return \Webman\Http\Response
     */
    protected function error(string $msg = 'error', int $code = 400)
    {
        return json([
            'code' => $code,
            'msg' => $msg
        ]);
    }

    protected function json(int $code, string $msg = 'ok', array $data = [])
    {
        return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
    }
} 